#!/bin/bash

APP_NAME=wishlist
CACHE_SIZE=1024m

cd "$(dirname "$0")/../backend" || {
  echo "该目录不存在: $(dirname "$0")/../backend"
  exit 1
}
BASE_DIR=$(pwd)
RUNTIME_DIR=$BASE_DIR/../runtime

COMMAND=$1
case $COMMAND in
help)
  cat "$BASE_DIR"/../bin/help.txt
  ;;
update)
  git pull --ff-only
  ;;
build)
  MODULE=$2
  MAVEN_MODULE=
  case $MODULE in
  standalone)
    MAVEN_MODULE=hospital-delivery-starters/hospital-delivery-starter-standalone
    ;;
  esac

  if [[ $MAVEN_MODULE != "" ]]; then
    mvn clean install -Dmaven.test.skip=true -pl $MAVEN_MODULE -am
  else
    mvn clean install -Dmaven.test.skip=true
  fi
  RESULT=$?

  [ $RESULT -ne 0 ] && echo "Maven构建失败"

  exit $RESULT
  ;;
start)
  MODULE=$2
  if test -z "$MODULE"; then
    echo "必须指定运行的模块"
    exit 1
  fi

  PORT=
  ENV=
  LOG_DIR=
  WAIT_FOR=0

  ARGS=$(getopt -o p:e:l:w:: --long port:,env:,logdir:,waitfor:: -- "$@")
  if [[ $? != 0 ]]; then
    echo "脚本执行异常"
    exit 1
  fi

  eval set -- "$ARGS"

  while true; do

    case $1 in
    -p | --port)
      PORT=$2
      shift 2
      ;;
    -e | --env)
      ENV=$2
      shift 2
      ;;
    -l | --logdir)
      LOG_DIR=$2
      shift 2
      ;;
    -w | --waitfor)
      WAIT_FOR=1
      shift 2
      ;;
    "--")
      shift
      break
      ;;
    *)
      echo "解析参数时出现未知异常: $1"
      exit 1
      ;;
    esac
  done

  DEFAULT_LOG_DIR=$BASE_DIR/../logs
  APP_LOG=
  case $MODULE in
  standalone)
    APP_LOG=standalone
    ;;
  *)
    echo "该模块不存在: [$MODULE]"
    exit 1
    ;;
  esac

  JAR_NAME=$BASE_DIR/target/$APP_NAME.jar
  if [ -z "$LOG_DIR" ]; then LOG_DIR=$DEFAULT_LOG_DIR; fi

  if [ ! -d "$LOG_DIR" ]; then
    echo "日志目录不存在, 将创建该目录: $LOG_DIR"
    mkdir -p "$LOG_DIR"
  fi

  PID_FILE=$RUNTIME_DIR/$MODULE/application.pid
  PORT_FILE=$RUNTIME_DIR/$MODULE/application.port

  # 关闭正在运行的应用(如果有)
  [ -f "$PID_FILE" ] && PREV_PID=$(cat "$PID_FILE")
  SHOULD_KILL=1
  [[ -n $PREV_PID && $PREV_PID != "" ]] || SHOULD_KILL=0

  if test $SHOULD_KILL -eq 1; then
    echo "应用正在运行, 将关闭当前应用并重新启动, 进程号: $PREV_PID"
    kill -9 "$PREV_PID"
    sleep 1
  fi

  [ -f "$PID_FILE" ] && rm -f "$PID_FILE"
  [ -f "$PORT_FILE" ] && rm -f "$PORT_FILE"

  JAVA_OPTS="-Xms$CACHE_SIZE -Xmx$CACHE_SIZE"
  [ -n "$ENV" ] && JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=$ENV"
  [ -n "$PORT" ] && JAVA_OPTS="$JAVA_OPTS -Dserver.port=$PORT"

  JAVA_OPTS="$JAVA_OPTS -Dlogging.file.path=$LOG_DIR"
  JAVA_OPTS="$JAVA_OPTS -Dspring.pid.fail-on-write-error=true"
  JAVA_OPTS="$JAVA_OPTS -Dspring.pid.file=$PID_FILE"
  JAVA_OPTS="$JAVA_OPTS -Dspring.portfile=$PORT_FILE"

  JAR_COMMAND="nohup java -jar $JAVA_OPTS $JAR_NAME >/dev/null 2>&1 &"
  echo "执行jar命令: $JAR_COMMAND"

  # 启动应用
  eval "$JAR_COMMAND"

  PID=$!
  LOG_FILE="$LOG_DIR/$APP_LOG/application.log"
  if [ "$MODULE" == 'standalone' ]; then
    LOG_FILE="$LOG_DIR/$APP_NAME/application.log"
  fi

  if [[ $WAIT_FOR -eq 1 ]]; then
    echo "正在启动, 进程号: $PID, 请稍后..."

    TAIL_CMD=
    if [[ -f "$LOG_FILE" && -n "$PID" ]]; then
      LAST_LINE=$(awk '{print NR}' "$LOG_FILE" | tail -n1)
      LAST_LINE=$((LAST_LINE + 1))
      TAIL_CMD="tail -n +$LAST_LINE -f --pid=$PID $LOG_FILE"
      eval "$TAIL_CMD" &
    fi

    if [ -n "$PID" ]; then
      while [[ ! -f $PORT_FILE ]]; do
        sleep 1
        PROCESS_STOP=$(ps -ef | grep $PID | grep -v grep | awk '{ print $2 }')
        if [[ -z $PROCESS_STOP ]]; then
          echo "启动失败, 日志: $LOG_FILE"
          exit 1
        fi
      done
    else
      echo "无法获取进程号, 启动失败"
      exit 1
    fi

    sleep 0.5
    if [ -n "$TAIL_CMD" ]; then
      TAIL_PID=$(ps -ef | grep "$TAIL_CMD" | grep -v grep | awk '{ print $2 }')
      kill -9 "$TAIL_PID"
      #      set +m kill -9 "$TAIL_PID" >/dev/null 2>&1
    fi
    echo "启动成功, 日志: $LOG_FILE"
    exit 0
  else
    echo "已启动, 请稍后查看启动状态, 日志: $LOG_FILE"
  fi
  ;;
*)
  echo "未知命令 [$COMMAND]."
  exit 1
  ;;
esac
exit 0
